package pattern.structural.composite;

import java.util.Iterator;
import java.util.Stack;

public class CompositeIterator implements Iterator<FileComponent>{

	private Stack<Iterator<FileComponent>> stack = new Stack<Iterator<FileComponent>>();
	
	public CompositeIterator(Iterator<FileComponent> it){
		stack.push(it);
	}
	
	@Override
	public boolean hasNext() {
		if(stack.empty()){
			return false;
		}else{
			Iterator<FileComponent> it = stack.peek();
			if(it.hasNext()){
				return true;
			}else{
				stack.pop();
				return hasNext();
			}
		}
	}

	@Override
	public FileComponent next() {
		if(hasNext()){
			Iterator<FileComponent> it = stack.peek();
			FileComponent fc = it.next();
			stack.push(fc.createIterator());
			return fc;
		}else{
			return null;
		}
	}

	@Override
	public void remove() {
		throw new UnsupportedOperationException();
	}
	
}
